# -*- coding: utf-8 -*-
# @Time    : 2024/8/29 12:14
# @Author  : Alvin
# @File    : sessions.py


from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import Relationship

from app.libs.error_code import AuthFailed
from app.libs.session import session_check
from app.models.access_tokens import AccessToken
from app.models.base import Base, db


class Session(Base):
    __tablename__ = 'sessions'
    user = Relationship("User", backref="sessions")
    id = Column(Integer, primary_key=True)
    user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
    session_token = Column(String(255), unique=True, nullable=False)

    # expires_at = Column(DateTime, nullable=False)

    @classmethod
    def check_session(cls, uid):
        session_obj = cls.query.filter_by(user_id=uid).first()
        if session_obj:
            open_id = session_obj.user.wechat_open_id
            # 获取access_token
            access_token = AccessToken.create_access_token(uid)
            try:
                check_session = session_check(session_obj, access_token, open_id)
            except AuthFailed as e:
                # print(e)
                # 这里要加入db上下文
                with db.auto_commit():
                    session_obj.delete()
                raise e
            return check_session, session_obj
        return False, None

        # else:
        #     wx_app_id = current_app.config.get('MINA_APP_ID')
        #     wx_secret = current_app.config.get('MINA_APP_SECRET')
        #     result = generate_session(wx_app_id, wx_secret, code)

        # 没有session则创建session

    @staticmethod
    def delete_session(session):
        session_obj = Session.query.filter_by(session_token=session).first()
        with db.auto_commit():
            session_obj.delete()

    @staticmethod
    def create_session(user_id, session_token):
        """
        创建一个新的会话记录。

        :param user_id: 用户ID
        :param session_token: 会话令牌
        :return: 新创建的会话对象
        """
        # 检查会话令牌是否唯一
        if Session.query.filter_by(session_token=session_token).first():
            return
        with db.auto_commit():
            # 创建新的会话对象
            new_session = Session()
            new_session.session_token = session_token
            new_session.user_id = user_id
            # 添加到数据库会话
            db.session.add(new_session)
